/*
 * Helper.cpp
 *
 *  Created on: Apr 17, 2017
 *      Author: zhangjf
 */

#include <Poco/AutoPtr.h>
#include <Poco/FileChannel.h>
#include <Poco/PatternFormatter.h>
#include <Poco/FormattingChannel.h>
#include <Poco/Zip/ZipArchive.h>
#include <Poco/Zip/ZipStream.h>
#include <Poco/StreamCopier.h>
#include <Poco/File.h>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
using namespace Poco;
using namespace Poco::Zip;

#include "Helper.h"

namespace util
{

void Helper::initLogger(Logger& pLog)
{
	AutoPtr<PatternFormatter> pPF(new PatternFormatter);
	pPF->setProperty("pattern", "%Y-%m-%d %H:%M:%S %s(%T): %t");
	pPF->setProperty("times","local");
	AutoPtr<FormattingChannel> pFC(new FormattingChannel(pPF));
	pLog.setChannel(pFC);
}

void Helper::initLogger(Logger& pLog, std::string& logFile)
{
	AutoPtr<FileChannel> pChannel(new FileChannel);
	pChannel->setProperty("path", logFile);
	pChannel->setProperty("rotation", " 20 M");
	pChannel->setProperty("archive", "timestamp");

	AutoPtr<PatternFormatter> pPF(new PatternFormatter);
	pPF->setProperty("pattern", "%Y-%m-%d %H:%M:%S %s(%T): %t");
	pPF->setProperty("times","local");
	AutoPtr<FormattingChannel> pFC(new FormattingChannel(pPF, pChannel));

	pLog.setLevel("debug");
	pLog.setChannel(pFC);
}

std::string str2hex(std::string& str)
{
	std::ostringstream oss;

	oss << hex << setfill('0') << setw(2);
	for (unsigned int i = 0; i < str.length(); ++i)
	{
		if ((i % 16) == 0)
			oss << std::endl;
		oss << (unsigned int) (unsigned char)str[i] << " ";
	}

	return oss.str();
}

bool Helper::readFileFromZip(const std::string& zipFile, std::string& subFile, std::string& outStr)
{

	std::ifstream ifs(zipFile.c_str(), ios::binary);
	ZipArchive arch(ifs);
	ZipArchive::FileHeaders::const_iterator it = arch.findHeader(subFile);
	if (it == arch.headerEnd())
	{
		return false;
	}

	ZipInputStream ins(ifs, it->second);
	ostringstream out(ios::binary);
	StreamCopier::copyStream(ins, out);
	outStr = out.str();

	return true;
}

std::string Helper::joinStrings(std::vector<std::string>& vecString, std::string& strSep)
{
	std::ostringstream oss;

	for (auto item : vecString)
	{
		oss << item << strSep;
	}

	std::string ret = oss.str();
	trim(ret, ", ");

	return ret;
}

void replaceSubString(std::string & s, std::string const & t, std::string const & w)
{
	string::size_type pos = s.find(t), t_size = t.size(), r_size = w.size();
	while (pos != std::string::npos)
	{ // found
		s.replace(pos, t_size, w);
		pos = s.find(t, pos + r_size );
	}
}

void Helper::escapeJsonString(std::string& str)
{
	replaceSubString(str, "\"", "\\\"");
}

} /* namespace util */
